package cn.jinjimi.app.main.adapter.pagerAdapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Roy
 * Date: 15/11/19
 */
public abstract class CyclePagerAdapter<E> extends PagerAdapter {
    private boolean mSuppportCycle = true;
    private List<E> mItems = new ArrayList<E>();

    public int getItemsSize() {
        return mItems != null ? mItems.size() : 0;
    }

    public void setItems(List<E> items) {
        if (items != null) {
            mItems = items;
        } else {
            if (mItems != null) {
                mItems.clear();
            }
        }
        notifyDataSetChanged();
    }

    public List<E> getItems() {
        return mItems;
    }

    public E getItem(int position) {
        if (position >= mItems.size())
            return null;
        return mItems != null ? mItems.get(position) : null;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object item) {
        if (item != null) {
            container.removeView((View) item);
        }
    }

    @Override
    public int getCount() {
        return (mSuppportCycle && getItemsSize() >= 2) ? Integer.MAX_VALUE : getItemsSize();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        position = position % getItemsSize();
        if (position < 0) {
            position = getItemsSize() + position;
        }

        View itemView = getView(container, position);
        if (null == itemView) return null;
        container.addView(itemView);
        return itemView;
    }

    public void setSupportCycle(boolean support) {
        mSuppportCycle = support;
    }

    public abstract View getView(ViewGroup container, int position);

}
